<?php

namespace app\common\model;

use think\Model;
use Carbon\Carbon;
use think\Exception;
use think\Lang;
use think\Request;
use think\Loader;
use app\common\traits\model\TraitModel;

class CarCalendar extends Model
{
    protected $table              = 'caravan_calendar';
    protected $autoWriteTimestamp = 'timestamp';
    protected $createTime         = 'created_at';
    protected $updateTime         = 'updated_at';
    protected $resultSetType      = 'collection';

    use TraitModel;

    public function caravan()
    {
        //字段太多就都取了
        return $this->belongsTo('\\app\\common\\model\\Caravans','caravan_id');
    }

    public function topics()
    {
        return $this->hasManyThrough('Calendar','Caravans', 'id', 'caravan_id','caravan_id');
    }

    public function camp()
    {
        return $this->belongsTo('\\app\\common\\model\\Camps','camp_id')->field('id,name,address,travel_money_base,rent_money_base');
    }

    /**
     * 检索房车列表
     * @param  array  $querys [description]
     * @return [type]         [description]
     */
    public function queryCaravans(array $querys = [], $page = 0)
    {
    	$after_date = Carbon::now()->addDay()->toDateString();

    	if (!array_key_exists('sdate', $querys) || empty($querys['sdate'])) {
    		$querys['sdate'] = $after_date;
    		//throw new Exception("Start date cannot be empty", 1);    		
    	}

    	if (!array_key_exists('edate', $querys) || empty($querys['edate'])) {
    		$querys['edate'] = Carbon::createFromFormat('Y-n-j', $querys['sdate'])->addYear()->toDateString();
    		//throw new Exception("End date cannot be empty", 1);    		
    	}

    	if (self::diffDays($querys['sdate'], $querys['edate'], false) < 0) {
            throw new Exception("End date must be greater than or equal to the start date", 1);      
        }

    	$day_two  = '(case when e > "' . $querys['edate'] . '" then "' . $querys['edate'] . '" else e end)';
    	$day_one  = '(case when s < "' . $querys['sdate'] . '" then "' . $querys['sdate'] . '" else s end)';
    	$diffdays = 'TIMESTAMPDIFF(DAY, ' . $day_one . ', ' . $day_two . ') AS diffdays';
        $field    = '*, ' . $diffdays . ', '. $day_one . ' AS sdate, ' . $day_two . ' AS edate';
    	
    	$citys = $this->getCitys();

        if (!is_array($querys['car_area'])) {
            if (array_key_exists('car_area', $querys) && array_key_exists($querys['car_area'], $citys)) {
            $car_area = $querys['car_area'];
            }else{
                $car_area = array_keys($citys);
            }
        }else{
            $car_area = $querys['car_area'];
        }

        //$user_id = session('user.id') ? session('user.id') : '';

        $lists = $this->with('camp,caravan')
             ->field($field)
             ->where(['s' => ['EGT', $after_date], 'sign' => 'shares', 'car_area' => ['IN', $car_area]])
             ->where(['user_id' => ['NEQ', Request::instance()->user ? Request::instance()->user->id : 0]])
             ->having('diffdays >= 0')
             ->order('diffdays, caravan_id ASC')
             ->limit($this->pagesize)
             ->page($page)
             ->select();

        foreach ($lists as $list) {
            $jps = Loader::model('Orders')->calculatePrice($list->caravan_id, $list->sdate, $list->edate);
            foreach ($jps as $jp) {
                $jp->ch_types = Lang::get($jp->types);
            }
            $list->jg = $jps;
        }

    	return $lists;
    }

    /**
     * 获取城市列表
     * @return [type] [description]
     */
    public function getCitys()
    {
    	$citys = [
    		'Beijing'  => Lang::get('beijing'), 
    		'Shanghai' => Lang::get('shanghai'),
    		'Sanya'    => Lang::get('sanya'),
    		'Chengdu'  => Lang::get('chengdu'),
    		'Xian'     => Lang::get('xian')
    	];
    	return $citys;
    }
    /**
     * [getCates 搜索页类型转换中文]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function getCates($id)
    {
        $grades = db('car_cates')->column('name', 'id');
        if (array_key_exists($id, $grades)) {
           return $grades[$id];
        }
        return '无';
    }
    public function getRadioName($value)
    {
        if (empty($value)) {
            return '无';
        }
        $status = ['1'=>'有','2'=>'无'];
        return $status[$value];
    }
    /**
     * 校验房车资源是否可以订单
     * @param  string $caravan_id [description]
     * @param  string $start_date [description]
     * @param  string $end_date   [description]
     * @return [type]             [description]
     */
    public function checkCanOrder(string $caravan_id, string $start_date, string $end_date)
    {
    	return $this->where(['caravan_id' => $caravan_id, 's' => ['ELT', $start_date], 'e' => ['EGT', $end_date]])->count() ? true : false;
    }

}